﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;

namespace Job.Web.Framework
{
    public class EnumLogic
    {
        /// <summary>
        /// 返回枚举中各项的集合
        /// </summary>
        /// <param name="enumType">枚举类型</param>
        /// <returns></returns>
        public static List<TypeItem> GetEnumCollection(Type enumType)
        {
            List<TypeItem> list = new List<TypeItem>();

            Array values = Enum.GetValues(enumType);
            for (int i = 0; i < values.Length; i++)
            {
                string name = Enum.GetName(enumType, values.GetValue(i));
                TypeItem item = new TypeItem(name, (int)values.GetValue(i));
                list.Add(item);
            }
            return list;
        }

        /// <summary>
        /// 返回枚举中各项的集合
        /// </summary>
        /// <param name="enumType">枚举类型</param>
        /// <returns>包含两列，第一列:Name, 第二列:Value</returns>
        public static DataTable GetEnumDataTable(Type enumType)
        {
            DataTable dt = new DataTable();
            dt.Columns.Add("Name", typeof(string));
            dt.Columns.Add("Value", typeof(int));

            Array values = Enum.GetValues(enumType);
            for (int i = 0; i < values.Length; i++)
            {
                DataRow dr = dt.NewRow();
                dr[0] = Enum.GetName(enumType, values.GetValue(i));
                dr[1] = (int)values.GetValue(i);
                dt.Rows.Add(dr);
            }
            return dt;
        }

        /// <summary>
        /// 获取枚举中的某项
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="value"></param>
        /// <returns></returns>
        public static T GetEnumItem<T>(int value)
        {
            Type type = typeof(T);
            if (Enum.IsDefined(type, value))
            {
                return (T)Enum.Parse(type, value.ToString());
            }
            throw new Exception("value is not in special Enum");
        }
    }


    [Serializable]
    public class TypeItem
    {
        string name;
        int value;

        public TypeItem()
        {
        }

        public TypeItem(string name, int value)
        {
            this.name = name;
            this.value = value;
        }

        public string Name
        {
            get
            {
                return name;
            }
            set
            {
                name = value;
            }
        }

        public int Value
        {
            get
            {
                return this.value;
            }
            set
            {
                this.value = value;
            }
        }
    }
}
